﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;

namespace RealTimeCharts.LineChart
{
    public class AxisWindow
    {
        /// <summary>
        /// 数据X轴、Y轴范围
        /// </summary>
        public DataWnd dataWnd;
        /// <summary>
        /// 包括title在内的矩形
        /// </summary>
        public Rect windowRect;

        /// <summary>
        /// 值坐标转换成像素坐标
        /// 需要提前设置数据窗口（windowRect),此窗口的位置可通过GetWindowRect函数获取
        /// </summary>
        /// <param name="p">值坐标</param>
        /// <returns></returns>
        public PixelPoint Point2Pixel(ValuePoint p)
        {
            PixelPoint pixelPt = new PixelPoint();

            double avaPixelSpanX = windowRect.Width;
            double avaPixelSpanY = windowRect.Height;

            ValueRange valueRangeAxisX = dataWnd.valueRangeX;
            ValueRange valueRangeAxisY = dataWnd.valueRangeY;

            double dataSpanX = valueRangeAxisX.maxValue - valueRangeAxisX.minValue;
            double dataSpanY = valueRangeAxisY.maxValue - valueRangeAxisY.minValue;

            if(dataSpanX == 0)
            {
                pixelPt.X = 0;
            }
            else
            {
                pixelPt.X = (int)(windowRect.X + (p.valX - valueRangeAxisX.minValue)/dataSpanX*avaPixelSpanX);
            }

            if(dataSpanY == 0)
            {
                pixelPt.Y = 0;
            }
            else
            {
                pixelPt.Y = (int)(windowRect.Y + (valueRangeAxisY.maxValue - p.valY)/dataSpanY * avaPixelSpanY);
            }

            return pixelPt;
        }

        /// <summary>
        /// 像素坐标转换成值坐标
        /// 需要提取设置数据窗口（windowRect)，此窗口的位置可通过GetWindowRect函数获取
        /// </summary>
        /// <param name="p"></param>
        /// <returns></returns>
        public ValuePoint Pixel2Point(PixelPoint p)
        {
            double avaPixelSpanX = windowRect.Width;
            double avaPixelSpanY = windowRect.Height;

            ValueRange valueRangeAxisX = dataWnd.valueRangeX;
            double dataSpanX = valueRangeAxisX.maxValue - valueRangeAxisX.minValue;

            ValueRange valueRangeAxisY = dataWnd.valueRangeY;
            double dataSpanY = valueRangeAxisY.maxValue - valueRangeAxisY.minValue;

            ValuePoint valuePoint = new ValuePoint();

            valuePoint.valX = valueRangeAxisX.minValue + (p.X - windowRect.X)/avaPixelSpanX * dataSpanX;
            valuePoint.valY = valueRangeAxisY.maxValue - (p.Y - windowRect.Y)/avaPixelSpanY * dataSpanY;

            return valuePoint;
        }
    }
}
